﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Reviewer.Entities;
using Reviewer.Entities.Services;
using Reviewer.Business;

public partial class CMSV2_Controls_Review_ReviewInfo : System.Web.UI.UserControl
{
    public int ReviewId
    {
        get
        {
            if (!String.IsNullOrEmpty(Request["ReviewId"]))
            {
                return int.Parse(Request["ReviewId"]);
            }
            return 0;
        }
    }

    public event TitleChangedDelegate TitleChanged;

    public void Refresh()
    {
        if (this.ReviewId <= 0)
        {
            this.uiPhInfo.Visible = false;
            this.uiPhSelectGame.Visible = true;
            this.uiBtnDelete.Enabled = false;
        }
        else
        {
            this.uiPhInfo.Visible = true;
            this.uiPhSelectGame.Visible = false;
            this.uiBtnDelete.Enabled = true;

            using (IMetadataService<Format> formatService = ServiceFactory.GetMetadataService<Format>())
            using (IGameService gameService = ServiceFactory.GameService)
            using (IReviewService service = ServiceFactory.ReviewService)
            {
                Review review = service.Find(this.ReviewId);
                this.GameId = review.GameId;

                Game item = gameService.GetBy(review.GameId);
                Format format = formatService.GetAll().FirstOrDefault(t => t.Id.Equals(item.Format));
                this.uiLitGame.Text = item.Title + " (" + (format == null ? "Ukendt format" : format.Name) + ")";
                BindAuthors();
                BindDistributers();

                this.uiTxtHeader.Text = review.Header;
                this.uiTxtText.Text = review.Text;
                this.uiRRating.CurrentRating = review.Rating;
                this.uiDdlAuthor.SelectedValue = review.Author.ToString();
                this.uiDdlDistributor.SelectedValue = review.Distributor.ToString();
            }
        }
    }

    private int GameId
    {
        get
        {
            if (ViewState["GameId"] == null)
            {
                return -1;
            }
            else
            {
                return (int)ViewState["GameId"];
            }
        }
        set
        {
            ViewState["GameId"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.Refresh();

            if (Request["GameId"] != null)
            {
                GameId = int.Parse(Request["GameId"]);
                this.uiBtnNext_OnClick(null, null);
            }
        }
    }

    protected bool uiRpSelectGame_OnIsRelationSelected(Type type, int id, Guid guid)
    {
        if (type.Equals(typeof(Game)))
        {
            return id.Equals(this.GameId);
        }
        return false;
    }

    protected void uiRpSelectGame_RelationSelected(Type type, int id, Guid guid)
    {
        if (type.Equals(typeof(Game)))
        {
            this.GameId = id;
        }
    }

    protected void uiRpSelectGame_RelationUnSelected(Type type, int id, Guid guid)
    {
        if (type.Equals(typeof(Game)))
        {
            this.GameId = -1;
        }
    }

    protected IEnumerable<Game> uiRpSelectGame_Prefilter(IEnumerable<Game> games)
    {
        List<Game> allGames = games.ToList();
        using (IReviewService service = ServiceFactory.ReviewService)
        {
            foreach (Review review in service.Find())
            {
                if (review.Id.Equals(this.ReviewId))
                {
                    continue;
                }
                else
                {
                    allGames.RemoveAll(t => t.Id.Equals(review.GameId));
                }
            }
        }
        return allGames.ToArray();
    }

    public void uiBtnNext_OnClick(object sender, EventArgs e)
    {
        if (this.GameId > 0)
        {
            this.uiPhSelectGame.Visible = false;
            while (this.uiPhSelectGame.Controls.Count > 0)
            {
                this.uiPhSelectGame.Controls.RemoveAt(0);
            }
            this.uiPhInfo.Visible = true;
            using (IMetadataService<Format> formatService = ServiceFactory.GetMetadataService<Format>())
            using (IGameService gameService = ServiceFactory.GameService)
            {
                Game item = gameService.GetBy(this.GameId);
                this.uiLitGame.Text = item.Title + " (" + (formatService.GetAll().FirstOrDefault(t => t.Id.Equals(item.Format)).Name) + ")";
            }
            BindAuthors();
            BindDistributers();
        }
    }

    private void BindAuthors()
    {
        using (IWriterService service = ServiceFactory.WriterService)
        {
            this.uiDdlAuthor.DataSource = service.Find().OrderBy(t => t.LogOnName);
            this.uiDdlAuthor.DataBind();
        }

        foreach (ListItem item in this.uiDdlAuthor.Items)
        {
            if (item.Text.ToUpperInvariant().Equals(Page.User.Identity.Name.ToUpperInvariant(), StringComparison.Ordinal))
            {
                item.Selected = true;
                break;
            }
        }
    }

    private void BindDistributers()
    {
        using (IDistributorService service = ServiceFactory.DistributorService)
        {
            this.uiDdlDistributor.DataSource = service.GetAll().OrderBy(t => t.Name);
            this.uiDdlDistributor.DataBind();
        }
    }

    protected void uiBtnDelete_Click(object sender, EventArgs e)
    {
        if (this.ReviewId > 0)
        {
            using (IReviewAdminService adminService = ServiceFactory.ReviewAdminService)
            {
                adminService.DeleteById(this.ReviewId);
            }

            Response.Redirect(ResolveUrl("~/cmsv2/ReviewsList.aspx"));
        }
    }

    protected void uiBtnSave_Click(object sender, EventArgs e)
    {
        Page.Validate();
        if (Page.IsValid)
        {
            using (IReviewAdminService adminService = ServiceFactory.ReviewAdminService)
            using (IReviewService service = ServiceFactory.ReviewService)
            {
                Review review = null;
                if (this.ReviewId > 0)
                {
                    review = service.Find(this.ReviewId);
                }
                else
                {
                    review = new Review();
                }

                review.GameId = this.GameId;
                review.Distributor = int.Parse(this.uiDdlDistributor.SelectedValue);
                review.Author = int.Parse(this.uiDdlAuthor.SelectedValue);
                review.Header = this.uiTxtHeader.Text;
                review.Text = this.uiTxtText.Text;
                review.Rating = this.uiRRating.CurrentRating;

                review = adminService.Save(review);

                if (this.ReviewId <= 0)
                {                  
                    Response.Redirect("ReviewManager.aspx?ReviewId=" + review.Id.ToString());
                }
            }
        }
    }
}
